package com.baymax.springboot.cli.controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * 测试子路径的controller
 *
 */
@Controller
@RequestMapping("/blog")
public class BlogController {

    /**
     * 访问路径是: http://localhost:8880/blog/name
     * @return
     */
    @GetMapping("/name")
    public String name(Model model) {
        //通过此方式传递给视图
        model.addAttribute("name", "BlogController");
        return "blog";
    }

    /**
     * 测试操作session
     * 获取HttpServletRequest对象进行操作
     *
     * http://localhost:8880/blog/name
     * http://localhost:8880/blog/name?code=123
     *
     * @param code
     * @param request
     * @return
     */
    @GetMapping("/session")
    public String session(@RequestParam(name="code", required=false) String code, HttpServletRequest request) {
        if(code != null) {
            /*设置session变量, thymeleaf 可通过此表达式${session.code}获取code*/
            request.getSession().setAttribute("code", code);
            return "blog";
        }

        //return "redirect:index"; //这样写会重定向到http://localhost:8880/blog/index
        //return "redirect:/index"; //这样写会重定向到http://localhost:8880/index

        /*这样写，springboot会去templates文件夹中寻找index.html*/
        //这样写会重定向到http://localhost:8880/
        return "redirect:/";
    }
}
